import { useState } from 'react'
import { Input, Button } from 'antd-mobile'
import { UserOutline, LockOutline, EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { setNickname, setToken } from '../../store/slices/userSlice'
import styles from './Login.module.css'
import { loginToken } from '../../services/api'
import { startRefreshLoop } from '../../services/authRefresh'
import { sm2EncryptHex } from '../../services/crypto'
import loginHeaderImg from '../../assets/login_header_back.png'
import loginLogoImg from '../../assets/login_logo.png'

export default function Login() {
  const navigate = useNavigate()
  const location = useLocation() as any
  const dispatch = useDispatch()

  const [mobile, setMobile] = useState('')
  const [password, setPassword] = useState('')
  const [showPwd, setShowPwd] = useState(false)

  const safeToast = (options: { icon: 'success' | 'fail'; content: string }) => {
    try {
      // lazy import 防止打包初始体积增加
      // eslint-disable-next-line @typescript-eslint/no-var-requires
      const { Toast } = require('antd-mobile')
      Toast.show(options)
    } catch (e) {
      console.error('Toast failed, fallback to alert:', e)
      if (typeof window !== 'undefined') {
        window.alert(options.content)
      }
    }
  }

  const onSubmit = async () => {
    if (!mobile.trim()) {
      safeToast({ icon: 'fail', content: '请输入手机号' })
      return
    }
    if (!password) {
      safeToast({ icon: 'fail', content: '请输入密码' })
      return
    }
    const PUBLIC_KEY = (import.meta as any).env?.VITE_SM2_PUBLIC_KEY as string
    const encPwd = PUBLIC_KEY ? sm2EncryptHex(password, PUBLIC_KEY, 0) : password
    const res: any = await loginToken({
      tenantId: '000000',
      account: mobile.trim(),
      password: encPwd,
    }).catch(() => null)
    if (!res) return
    const token = res?.accessToken
    const nickname = res?.userName || res?.account || '用户'
    if (!token) {
      safeToast({ icon: 'fail', content: '登录失败：未获取到凭证' })
      return
    }
    dispatch(setToken(token))
    dispatch(setNickname(nickname))
    if (typeof window !== 'undefined') {
      window.localStorage && window.localStorage.setItem('authInfo', JSON.stringify(res))
    }
    // 启动全局定时刷新
    try {
      startRefreshLoop()
    } catch {}
    const redirect = location?.state?.from?.pathname || '/home'
    navigate(redirect, { replace: true })
  }

  return (
    <div className={styles['login-page']}>
      {/* 头部图片 */}
      <img src={loginHeaderImg} alt="登录头部" className={styles['login-header']} />

      {/* 返回按钮 */}
      {/* <NavBar back onBack={() => navigate(-1)} className={styles['login-navbar']} /> */}

      <div className={styles['login-title']}>
        <img src={loginLogoImg} alt="logo" className={styles['login-logo']} />
        <div className={styles['brand']}>欢迎登录 惠青家</div>
      </div>

      <div className={styles['login-form']}>
        <div className={styles['input-item']}>
          <span className={styles['prefix']}>
            <UserOutline />
          </span>
          <Input
            value={mobile}
            onChange={val => setMobile(val)}
            placeholder="请输入手机号"
            clearable
          />
        </div>

        <div className={styles['input-item']}>
          <span className={styles['prefix']}>
            <LockOutline />
          </span>
          <Input
            value={password}
            onChange={val => setPassword(val)}
            type={showPwd ? 'text' : 'password'}
            placeholder="请输入密码"
            clearable
          />
          <span className={styles['suffix']} onClick={() => setShowPwd(v => !v)}>
            {showPwd ? <EyeOutline /> : <EyeInvisibleOutline />}
          </span>
        </div>

        <div className={styles['assist-row']}>
          <a
            className={styles['link']}
            onClick={() => safeToast({ icon: 'fail', content: '请联系管理员' })}
          >
            忘记密码？
          </a>
        </div>

        <Button
          block
          size="large"
          className={`${styles['login-btn']} ${styles['primary']}`}
          onClick={onSubmit}
        >
          登录
        </Button>
      </div>
    </div>
  )
}
